var pomelo = require('pomelo');
var utils = require('../util/utils');
var logger = require('pomelo-logger').getLogger('model',__filename);
var model = module.exports;

var playerInfoField =
{
    '_id':0,
    'playerId':1,
    'nickName':1,
    'coinNum':1,
    'diamondNum':1,
    'power':1,
    'winRate':1,
    'fightRecord':1,
    'star':1,
    'actors':1,
    'bag':1,
    'guide':1
};
var rankField =
{
    '_id':0,
    'playerId':1,
    'nickName':1,
    'winRate':1,
    'fightRecord':1,
    'star':1
}
var sortField =
{
    'fightRecord':-1,
    'winRate':-1,
    'star':-1
}
//获得玩家为激活角色列表
model.getUnActiveActor = function(playerId,cb)
{
    var actor_list = [];
    var dbClient = pomelo.app.get('dbClient');
	var db_cb = function(error,collection)
	{
		collection.findOne({'playerId':playerId},function(error,res)
		{
			if(error)
			{
				logger.error(error);
			}
			else
			{
				var actors = res.actors;
				for( var i = 0;i < actors.length;i++ )
				{
					var actor = actors[i];
					if( 0 == actor.active )
					{
						actor_list.push(i+1);
					}
				}
				utils.invokeCallback(cb,null,actor_list);
			}
		});
	}
    dbClient.collection('player',db_cb);
}
model.getNews = function(cb)
{
    var dbClient = pomelo.app.get('dbClient');
    var db_cb = function(error,collection)
    {
        var field =
        {
            '_id':0,
            'notice':1,
            'state':1
        }
        collection.find({'state':1},field).toArray(function(err,res)
        {
            if( err )
            {
                logger.error(err);
            }
            else
            {
                utils.invokeCallback(cb,null,res);
            }
        });
    }
    dbClient.collection('news',db_cb);
}
model.getActorExp = function(player,cb)
{
    var playerId = player.uid;
    var actorId = player.aid;
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'playerId':1,
            'actors':1
        }
        collection.findOne({'playerId':playerId},field,function(err,res)
        {
            if( res )
            {
                cb(res.actors[actorId-1].experience);
            }
            else
            {
                cb(0);
            }
        })
    })
}
//获得排名
model.getRank = function(playerId,cb)
{
    var dbClient = pomelo.app.get('dbClient');

    dbClient.collection('player',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'playerId':1,
            'fightRecord':1,
            'star':1,
            'winRate':1
        };
        collection.find({},field).sort(sortField).limit(99).toArray(function(err,res)
        {
            if( res )
            {
                for( var i in res )
                {
                    if( playerId == res[i].playerId )
                    {
                        i++;
                        cb(i);
                        return;
                    }
                }
                cb(100);
            }
            else
            {
                console.info("get rank error");
                cb(100);
            }
        })
    })
}
//创建用户
model.createPlayer = function(args,cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.find().sort({'playerId':-1}).limit(1).toArray(function(err,res)
        {
            var actors = [];
            for ( var i = 0;i < 7;i++ )
            {
                if( 0 == i )
                {
                    actors.push({'experience':0,'second':0,'active':1});
                }
                else
                {
                    actors.push({'experience':0,'second':0,'active':0});
                }
            }
            var reg_time = utils.getTime();
            var nickName = 'dy_'+ utils.randomString(4);
            var newPlayer =
            {
                'playerId'      :args.playerId,
                'nickName'       : nickName,

                'coinNum'       :200,
                'diamondNum'    :0,
                'power'         :10,

                'fightRecord'   :20,
                'star'          :1,
                'winNum'        :0,
                'defeatNum'     :0,
                'winRate'       :0,

                'reg_time'      :reg_time,
                'last_login'    :reg_time,

                'imei'          :args.imei,
                'imsi'          :args.imsi,
                'model'         :args.model,
                'gameId'        :args.gameId,
                'gameVer'       :args.gameVer,
                'os'            :args.os,

                'missionId'     :1,
                'guide'          :0,
                'login_count'   :1,

                'bag'           :[],
                'actors'        :actors
            };

            if( res.length > 0 && !(newPlayer.playerId) )
            {
                console.info("res:",res);
                newPlayer.playerId = res[0]['playerId'] + 1;
            }
            collection.insert(newPlayer);
            var res =
            {
                'playerId'      :newPlayer.playerId,
                'nickName'      :newPlayer.nickName,

                'coinNum'       :newPlayer.coinNum,
                'diamondNum'    :newPlayer.diamondNum,
                'power'          :newPlayer.power,

                'scoreRank'     :newPlayer.playerId,

                'fightRecord'   :newPlayer.fightRecord,
                'star'           :newPlayer.star,
                'winNum'         :newPlayer.winNum,

                'actors'         :newPlayer.actors,
                'bag'            :newPlayer.bag
            };
            utils.invokeCallback(cb,null,res);
        });
    });
};
//获取玩家信息
model.getPlayerInfo = function(playerId ,cb)
{
    var db = pomelo.app.get('dbClient');
    var self = this;
    db.collection('player',function(err,collection)
    {
        collection.findOne({'playerId':playerId},playerInfoField,function(err,res)
        {
            if( res )
            {
                module.exports.getRank(res.playerId,function(rank)
                {
                    res.scoreRank = rank;
                    console.info("get rank:",rank);
                    utils.invokeCallback(cb,null,res);
                })
            }
            else
            {
                console.info("player not found");
                utils.invokeCallback(cb,null,null);
            }
        });
    });
};
//战斗结果处理
model.doResult = function(playerId,result,cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'playerId':1,
            'winNum':1,
            'defeatNum':1,
            'star':1,
            'fightRecord':1,
            'winRate':1
        }
        collection.findOne({'playerId':playerId},field,function(err,res)
        {
            if( result )//胜利
            {
                res.star++;
                res.winNum++;
                if( res.star > 3 )
                {
                    res.star = 1;
                    res.fightRecord++;
                }
            }
            else//失败
            {
                res.star--;
                res.defeatNum++;
                if( res.star < 1 )
                {
                    res.star = 3;
                    res.fightRecord--;
                    if( res.fightRecord < 0 )
                    {
                        res.fightRecord = 0;
                    }
                }
            }
            res.winRate = Math.round(res.winNum * 100 / (res.winNum + res.defeatNum));
            console.info('update:',res);
            collection.update({'playerId':playerId},{$set:res},function(err,updateRes)
            {
                if( res )
                {
                    res.result = Math.abs(result - 1);
                    utils.invokeCallback(cb,null,res);
                }
            })
        })
    })
}
//登录奖励
model.loginWard = function(playerId)
{
    var now = utils.dateToString(new Date());
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({"playerId":playerId},function(err,res)
        {
            var last = new Date(res.loginTime);
            var test = new Date(now);
            var loginTimes = res.loginTimes ;
            var differ = parseInt(Math.abs(test - last) /1000/60/60/24);
            logger.info('differ====================>',differ);
            if(1 == differ)
            {
                var loginTime = now;
                var newLoginTimes  = loginTimes + 1 ;
                collection.update
                (
                    {"playerId":playerId},
                    {$set:{"loginTime":loginTime,"loginTimes":newLoginTimes}},
                    function(err,res)
                    {
                        if(err) throw err;
                    }
                );
            }
            else if(differ >= 2)
            {
                var loginTime = now ;
                var newLoginTimes = 1 ; // 将连续登录的次数设置�?
                collection.update
                (
                    {"playerId":playerId},
                    {$set:{"loginTime":loginTime,"loginTimes":newLoginTimes}},
                    function(err,res)
                    {
                        if(err) throw err;
                    }
                );
            }
        });
    });
};
//获取技能数值
model.getAllSkillValue = function(cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('value',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'piece':1,
            'attr':1,
            'skill':1,
            'actor':1,
            'prop':1
        };
        collection.findOne({},field,function(err,res)
        {
            utils.invokeCallback(cb ,null,res);
        });
    });
};
//生成卡牌数据
model.createCardList = function(playerId,cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('card',function(err,collection)
    {
        collection.findOne({},function(err,res)
        {
            var package_sum = res.package_list.length;//4
            var high_sum = res.high_list.length;//7
            var mid_sum = res.mid_list.length;//9
            var low_sum = res.low_list.length;//5

            var package_count = Math.round(Math.random());//从4个随机选取0-1个礼包
            var high_count = Math.round(Math.random()+1);//从7个随机选取1-2个高价卡牌
            var mid_count = Math.round(Math.random()*2+3);//从9个随机选取3-5个中价卡牌
            var low_count = 10 - (package_count + high_count + mid_count);//从5个随机选取2-6个底价卡牌

            var card_list = [];

            var high_start_index = Math.round(Math.random()*(high_sum-1));//编号0-6
            var mid_start_index = Math.round(Math.random()*(mid_sum-1));//编号0-8
            var low_start_index = Math.round(Math.random()*(low_sum-1));//编号0-4

            var tmp_list = [];
            for( i = 0;i < high_count;i++ )
            {
                tmp_list.push(res.high_list[high_start_index]);
                high_start_index++;
                if( high_sum == high_start_index )
                {
                    high_start_index = 0;
                }
            }
            for( i = 0;i < mid_count;i++ )
            {
                tmp_list.push(res.mid_list[mid_start_index]);
                mid_start_index++;
                if( mid_sum == mid_start_index )
                {
                    mid_start_index = 0;
                }
            }
            for( i = 0;i < low_count;i++ )
            {
                tmp_list.push(res.low_list[low_start_index]);
                low_start_index++;
                if( low_sum == low_start_index )
                {
                    low_start_index = 0;
                }
            }
            //分析随机抽取的卡牌数据
            var coin_list = [];
            var prop_list = [];
            var power_list = [];

            for ( i = 0;i < tmp_list.length;i++ )
            {
                var item = tmp_list[i];
                if ( 1 == item.id )//金币类型卡牌
                {
                    coin_list.push(item.num);
                }
                if ( 2 == item.id )
                {
                    var prop_item =
                    {
                        "id":item.propId,
                        "num":item.num
                    };
                    prop_list.push(prop_item);
                }
                if ( 3 == item.id)
                {
                    power_list.push(item.num);
                }
            }


            if(coin_list.length)
            {
                card_list.push({"id":1,"num":coin_list});
            }
            if(prop_list.length)
            {
                card_list.push({"id":2,"prop":prop_list});
            }
            if(power_list.length)
            {
                card_list.push({"id":3,"num":power_list});
            }
            if( package_count )
            {
                var package_index = Math.round(Math.random()*(package_sum-1));
                var package_item = res.package_list[package_index];
                for( var i in package_item )
                {
                    //判断礼包中角色卡牌
                    if( 5 == package_item[i].id )
                    {
                        package_item.slice(i,1);
                        model.getUnActiveActor(playerId,function(error,res)
                        {
                            if(error)
                            {
                                logger.info(error);
                            }
                            else
                            {
                                var actorId_index = Math.round(Math.random()*(res.length-1));
                                var actorId = res[actorId_index];
                                var actor_item =
                                {
                                    "id":5,
                                    "actorId":actorId
                                };
                                package_item.push(actor_item);
                            }
                        });
                    }
                }
                card_list.push({"id":4,"package":package_item});
            }
            console.info
            (
                "随机生成低价卡牌%d个,中价卡牌%d个,高价卡牌%d个,礼包%d个\n",
                low_count,
                mid_count,
                high_count,
                package_count
            );
            console.info
            (
                "其中金币卡牌%d个,道具卡牌%d个,体力卡牌%d个",
                coin_list.length,
                prop_list.length,
                power_list.length
            );
            var retJson = {"cardList":card_list};
            utils.invokeCallback(cb,null,retJson);
        });
    });
};
//获取排行榜
model.getScoreList = function(cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.find({},rankField).sort(sortField).limit(20).toArray(function(err,res)
        {
            for( var i in res )
            {
                res[i].winRate = res[i].winRate || 0;
            }
            utils.invokeCallback(cb,null,res);
        });
    });
};
//登陆记录
model.doLogin = function(playerId)
{
    var time = utils.getTime();
    var dbClient = pomelo.app.get('dbClient');
    var cb = function(err,collection)
    {
        var condition = {'playerId':playerId};
        var update = 
        {
            $set:{'last_login':time},
            $inc:{'login_count':1}
        }
        collection.update(condition,update);
    }
    dbClient.collection('player',cb);
}
//角色购买
model.actorBuy = function(playerId,actorId)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('value',function(err,collection)
    {
        collection.findOne({} , function(err,res)
        {
            var cost = res.actor[actorId-1];
            dbClient.collection('player',function(err,collection2)
            {
                collection2.findOne({"playerId" :playerId},function(err,res2)
                {
                    var data = res2.actors ;
                    data[actorId-1].active = 1;
                    var coinNum  = res2.coinNum -cost ;
                    if( coinNum >= 0)
                    {
                        collection2.update({"playerId" : playerId},{$set:{actors:data,coinNum:coinNum}},function(err,res3){}); //更新用户角色信息
                    }
                });
            });
        });
    });
};
//商城 购买花钱买金币
model.goodsBuy = function(playerId,goodsId)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('shop',function(err,collection)
    {
        collection.findOne({},function(err,res)
        {
            var coinNum = res.coinList[goodsId-1].num;
            dbClient.collection('player',function(err,collection2)
            {
                var update = {$inc:{'coinNum':coinNum}}
                collection2.update({'playerId':playerId},update,function(err,res2)
                {

                });
            });
        });
    });
};

//获取商店信息
model.getShopInfo = function(cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('shop',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'propList':1,
            'powerList':1,
            'coinList':1,
            'diamondList':1,
            'wordList':1,
            'openSecond':1
        }
        collection.findOne({},field,function(err,res)
        {
            utils.invokeCallback(cb,null,res);
        });
    });
};
//玩家赚取信息
model.playerEran = function(playerId,coinNum)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var condition = {"playerId":playerId};
        var update = {$inc:{'coinNum':coinNum}};
        var cb = function(err,res)
        {
            if(err)
            {
                logger.error(err);
            }
            else
            {
                
            }
        };
        collection.update(condition,update,cb);
    });
};
//每日任务列表
model.getDayTaskList = function(cb)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('dayTask',function(err,collection)
    {
        collection.findOne({},function(err,res)
        {
            var dayTask =
            {
                list:res.dayTaskList,
                ver :res.ver
            };
            utils.invokeCallback(cb ,null, dayTask );
        });
    });
};
//获取机器
model.getRobot = function(playerId,actorId ,cb)
{
    var dbClient = pomelo.app.get('dbClient');
    var self = this;
    var table = 'player';
    dbClient.collection(table,function(err,collection)
    {
        collection.findOne({'playerId':playerId},function(err,res)
        {
            dbClient.collection(table,function(err,collection2)
            {
                var robots = [];
                collection2.find({'playerId':{$lt:100}}).toArray(function(err,res2)
                {
                    for(var i = 0 ; i < res2.length; i++)
                    {
                        var player = res2[i];
                        var actors = player.actors;
                        var resultId = player.playerId ;
                        for(var j = 0 ; j < actors.length ; j++)
                        {
                            if( playerId != resultId )
                            {
                                var actor =
								{
									'actorId':j+1,
									'experience':actors[j].experience
								};
								var robot =
								{
									'playerId':player.playerId,
									'nickName':player.nickName,
									'fightRecord':player.fightRecord,
									'actor':actor
								};
								robots.push(robot);
                            }
                        }
                    }
					if(robots.length)
					{
						var ranNum = Math.round(Math.random()*(robots.length-1));
						var robot = robots[ranNum];
						module.exports.getRank(robot.playerId,function(rank)
						{
							robot.scoreRank = rank;
							console.info('robot matched:',robot);
							utils.invokeCallback(cb ,null,robot);
						})
					}
                });
            });
        });
    });
};
//获取玩家战斗信息
model.getFightInfo = function(player,cb)
{
    var playerId = player.uid;
    var actorId = player.aid;
    var self = this;
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var field =
        {
            '_id':0,
            'playerId':1,
            'nickName':1,
            'fightRecord':1,
            'actors':1,
            'score':1
        }
        collection.findOne({'playerId':playerId},field,function(err,res)
        {
            var actor =
            {
				'actorId':actorId,
                'experience':res.actors[actorId-1].experience
            };
			var retPlayer =
			{
				'playerId':playerId,
				'nickName':res.nickName,
				'fightRecord':res.fightRecord,
				'actor':actor
			};
            module.exports.getRank(playerId,function(rank)
            {
                retPlayer.scoreRank = rank;
                console.info('fight info:',retPlayer);
                utils.invokeCallback(cb ,null,retPlayer);
            })
        });
    });
};
//通过imei查找用户
model.getPlayerInfoByImei= function(imei,cb)
{
    var dbClient = pomelo.app.get('dbClient');
    var self = this;
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({'imei':imei},playerInfoField,function(err,res)
        {
            if( res )
            {
                module.exports.getRank(res.playerId,function(rank)
                {
                    res.scoreRank = rank;
                    utils.invokeCallback(cb ,null,res);
                })
            }
            else
            {
                utils.invokeCallback(cb ,null,null);
            }
        });
    });
};

//道具购买
model.propBuy  = function(playerId,props,coinNum)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({"playerId":playerId},function(err,res)
        {
            var bag = res.bag ;
            if(bag == null || bag.length == 0 )
            {
                console.log('bag is null') ;
                bag = props;
            }
            else
            {
                for(var i =0 ;i<props.length ;i++)
                {
                    var propId = props[i].id ;
                    var num  = props[i].num ;
                    var isJoin = false ;
                    for(var j = 0 ;j<bag.length ;j++)
                    {
                        var temp = bag[j].id;
                        var newNum = bag[j].num ;
                        if(propId == temp)
                        {
                            bag[j].num = newNum + num ;
                            isJoin  = true ;
                        }
                    }
                    if(!isJoin)
                    {
                        var join = {'id':propId ,'num':num};
                        bag[bag.length] = join ;
                    }
                }
            }
            var coin = res.coinNum - coinNum ;
            logger.info('bag============>',bag);
            if( coin > 0 )
            {
                collection.update({"playerId" : playerId},{$set:{coinNum:coin ,bag:bag}},function(err,res)
                {

                });
            }
        });
    });
};
//体力购买
model.powerBuy  = function(playerId,powerId)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('shop',function(err,collection)
    {
        collection.findOne({},function(err,res)
        {
            var value = res.powerList[powerId-1].num;  //购买体力
            var coin  = res.powerList[powerId-1].coin; //所需金币
            dbClient.collection('player',function(err,collection2)
            {
                collection2.update({'playerId':playerId} ,{$inc:{power:value,coinNum:-coin}},function(err,res2)
                {

                });
            });
        });
    });
};
//道具使用
model.propUse = function(playerId,propId)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({"playerId":playerId},function(err,res)
        {
            var bag = res.bag ;
            for( var i = 0; i < bag.length;i++ )
            {
                var temp = bag[i].id ;
                var newNum = bag[i].num ;
                if(newNum > 0)
                {
                    if(propId == temp)
                    {
                        bag[i].num = newNum -1;
                    }
                }
            }
            collection.update({"playerId" : playerId},{$set:{bag:bag}},function(err,res)
            {
            });
        });
    });
};
//开启第二技激活
model.secondOpen = function(playerId,actorId)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({"playerId":playerId},function(err,res)
        {
            var actors = res.actors ;
            actors[actorId-1].second = 1 ;
            var coinNum = res.coinNum - 200 ;
            var set =
            {
                'actors':actors,
                'coinNum':coinNum
            };
            collection.update({"playerId":playerId},{$set:set},function(err,res)
            {
            });
        });
    });

};

//同步经验
model.expSync = function(playerId,actorId,exp)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        collection.findOne({'playerId':playerId},function(err,res)
        {
            var actors = res.actors;
            actors[actorId-1].experience = exp;
            collection.update({"playerId" : playerId},{$set:{'actors':actors}},function(err,res)
            {
            });
        });
    });
};
//玩家信息的同步
model.playerInfoSync = function(playerId,args)
{
    var playerInfo = args.player;
    console.log('playerInfo Sync:%j',args);
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var update =
        {
            $set:
            {
                'coinNum':playerInfo.coinNum,
                'power':playerInfo.power,
                'missionId':playerInfo.missionId,
                'actors':playerInfo.actors,
                'bag':playerInfo.bag
            }
        }
        collection.update({'playerId':playerId},update,function(err,res){});
    });
};

model.syncPlayer = function(uid,update)
{
    var dbClient = pomelo.app.get('dbClient');
    dbClient.collection('player',function(err,collection)
    {
        var set =
        {
            $set:update
        }
        collection.update({'playerId':uid},set,function(err,res)
        {

        });
    });
}